package com.hunglv.databasehelper;

import com.hunglv.entity.*;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;

public class SetAlarmLocationDatabaseHelper extends SQLiteOpenHelper {
	private SQLiteDatabase db;
	private final Context context;

	public static String DB_NAME = "set_alarm_location";
	private static String TABLE_NAME = "location";

	private static String KEY_ID = "_id";
	public static int COLUMN_ID = 0;
	private static String KEY_STOP_ID = "stop_id";
	public static int COLUMN_STOP_ID = 1;

	private static final int DB_VERSION = 1;
	private static final String DATABASE_CREATE = "create table " + TABLE_NAME
			+ " (" + KEY_ID + " integer primary key, " + KEY_STOP_ID
			+ " int);";

	public SetAlarmLocationDatabaseHelper(Context context) {
		super(context, DB_NAME, null, DB_VERSION);
		this.context = context;
	}

	@Override
	public void onCreate(SQLiteDatabase _db) {
		_db.execSQL(DATABASE_CREATE);
	}

	@Override
	public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
		_db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
		onCreate(_db);
	}

	public void open() throws SQLiteException {
		try {
			db = this.getWritableDatabase();
		} catch (SQLiteException e) {
			db = this.getReadableDatabase();
		}
	}

	public void close() {
		db.close();
	}

	public Cursor getAllCursor() {
		Cursor result = db.query(TABLE_NAME, new String[] { KEY_ID,
				KEY_STOP_ID }, null, null, null, null, null);
		return result;
	}

	public long insertStopLocation(StopItem item) {
		ContentValues cv = new ContentValues();
		cv.put(KEY_STOP_ID, item.getId());

		return db.insert(TABLE_NAME, null, cv);
	}

	public boolean removeStopLocation(int _id) {
		return db.delete(TABLE_NAME, KEY_ID + "=" + _id, null) > 0;
	}

	public Context getContext() {
		return context;
	}
}
